<?php

App::uses('AdminController', 'Controller');

class AdminProductsController extends AdminController{
	
	public $uses = array('Product', 'Category');
	public $paginate = array( 'limit' => ITEMS_PER_PAGE, 'order'=>'Product.name' );
	
	private function _commonData() {
		$this->set('allcategories', $this->Category->find("list"));
        $this->set('categoryTree',  $this->Category->tree());
	}
	
	public function index(){
		$this->_commonData();
		
		$conditions = array();
		if($this->request->is('post')) {
			$filter = $this->data['Filter'];
			
			if(!empty($filter['category_id'])) {
				$conditions['Product.category_id'] = $filter['category_id'];
			}
			
			if(!empty($filter['kword'])) {
				$conditions['Product.name LIKE'] = '%' . $filter['kword'] . '%';
			}
			$this->set("filter", $filter);
		}
		
		$this->set('products', $this->paginate('Product', $conditions));
	}
	
	public function create(){
		$this->_commonData();
		
		$this->set('product',$this->Product->create());
		$this->render('form');
	}
	
	public function edit($id){
		$this->_commonData();
		$this->set('product',$this->Product->findById($id));
		$this->render('form');
	}
	
	public function save(){
		if($this->request->is('post')){
			
			$this->Product->set($this->data);
			if($this->Product->validates()) {
				$data = $this->data;
				$toupload = array();
				foreach($data['ProductImage'] as $k=>$product_image) {
					if(isset($product_image['file'])) {
						if(!$product_image['file']['error']){
							$toupload[] = $product_image['file'];
							$data['ProductImage'][$k]['src'] = $product_image['file']['name'];
						}else{
							unset($data['ProductImage'][$k]);
						}
					}
				}
				
				$imagesBeforeSave=array();
				if($this->Product->id>0) {
					$imagesBeforeSave = $this->Product->ProductImage->find("all", array("fields"=>array("src"), "conditions"=>array("product_id"=>$this->Product->id)));
					$imagesBeforeSave = Set::extract($imagesBeforeSave, '/ProductImage/src');
					$this->Product->ProductImage->deleteAll(array('product_id'=>$this->Product->id));
				}
				$imagesAfterSave = Set::extract($data, 'ProductImage.{n}.src');
				$forDelete = array_diff($imagesBeforeSave, $imagesAfterSave);
				
				if($this->Product->saveAll($data)){
					$products_img_folder = 'img' . DS . 'products' . DS . $this->Product->id;
					
					foreach($forDelete as $image){
						@unlink($products_img_folder . DS . $image);
					}
					foreach($toupload as $file) {
						upload($file['tmp_name'], $products_img_folder . DS . $file['name']);
					}
					
					$this->setFlash('Proizvod je sačuvan', 'ok');
					$this->redirect('/admin_products/edit/'.$this->Product->id);
				}else{
					$this->setFlash('Proizvod nije sačuvan!');
					return $this->render('form');
				}
			}
			$this->setFlash('Podaci nisu validni.');
			return $this->render('form');
		}
		$this->redirect('/admin_products');
	}
	
	public function delete($id){
		if($this->Product->delete($id)) {
			$this->setFlash("Proizvod #{$id} je obrisan.", 'ok');
		}else{
			$this->setFlash("Proizvod #{$id} nije obrisan.");
		}
		$this->redirect('/admin_products');
	}
	
	public function categories(){
		$this->_commonData();
	}
	
	public function category_create(){
	    $this->_commonData();
		$this->set('category', $this->Category->create());
		$this->render('category_form');
	}

	public function category_edit($id){
	    $this->_commonData();
		$this->set('category', $this->Category->findById($id));
		$this->render('category_form');
	}

	public function category_save(){
		if($this->request->is('post')) {
			$data = $this->data;
			
			// update category key
			$data['Category']['key'] = urlize($data['Category']['name']);
			// update the image
			$file = $data['CategoryImage']['file'];
			if(!$file['error']) {
				preg_match('/\..*?$/', $file['name'], $ext);
				$data['Category']['image'] = $data['Category']['key'] . $ext[0];
			}
			
			$this->Category->set($data);
			if($this->Category->validates()){
				if($this->Category->save($data)){
					// upload the image
					upload($file['tmp_name'], 'img' . DS . 'categories' . DS . $data['Category']['image']);
					
					$this->setFlash('Kategorija je sačuvana', 'ok');
					$this->redirect('category_edit/'.$this->Category->id);
				}else{
				    $this->_commonData();
					$this->setFlash('Kategorija nije sačuvana. Proverite unete podatke i pokušajte ponovo');
					$this->set('category', $data);
					return $this->render('category_form');
				}
			}else{
			    $this->_commonData();
				$this->setFlash('Uneti podaci nisu validni. Proverite unete podatke i pokušajte ponovo');
				$this->set('category', $data);
				return $this->render('category_form');
			}
		}
		$this->redirect("categories");
	}
	
	public function category_delete($id){
		if($this->Category->delete($id)) {
			$this->setFlash("Kategorija proizvoda #{$id} je obrisana.", 'ok');
		}else{
			$this->setFlash("Kategorija proizvoda #{$id} nije obrisana.");
		}
		$this->redirect('/admin_products/categories');
	}
    
    public function category_positions_update() {
        $this->autoRender = false;
        $pos = $this->params->query['positions'];
        foreach($pos as &$p) {
            $p = array(
                'Category' => $p
            );
        }
        
        if ($this->Category->saveAll($pos)) {
            echo 'Redosled je uspešno sačuvan.';
        } else {
            echo 'Redosled nije sačuvan!';
        }
    }
	
}
